package com.younion.action.manage;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;

import com.younion.business.IRolesService;
import com.younion.business.IUserService;
import com.younion.common.base.BaseAction;
import com.younion.common.constants.RoleType;
import com.younion.common.paginator.Paginator;
import com.younion.permission.NodePermission;
import com.younion.permission.PermissionUtil;
import com.younion.util.SimpleWorkbook;
import com.younion.util.SimpleWorkbook.RowMapper;
import com.younion.vo.CustomerVO;
import com.younion.vo.UserVO;

import cpcns.jhsks.util.MapCollectionUtils;

/**
 * @author seagull
 */
public class UserAction extends BaseAction {

	protected static final Log logger = LogFactory.getLog(UserAction.class);

	private IUserService userService = null;

	@Autowired
	private IRolesService rolesService = null;

	private UserVO userVO = new UserVO();

	private List<UserVO> userList;// 结果集列表

	private Collection roles;

	private File importFile;
	
	private String searchType;

	/**
	 * 列表：翻页区；数据区
	 */
	@RequiresPermissions("listUser")
	public String listUser() {
		try {
			if(getSessionUser().getCustomer() != null){
				userVO.setCustomerId(getSessionUser().getCustomer().getId());
			}else if(userVO!=null && userVO.getCustomerId() != null){
				userVO.setCustomer(new CustomerVO(userVO.getCustomerId()));
			}
			Map paramMap = null;
			if (userVO != null) {
				paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(userVO));
			}
			
			// 获取总记录数
			int total = userService.getCountByMap(paramMap);
			// 根据总记录数获取分页对象
			Paginator paginator = this.getPaginator(total);
			userList = userService.get(paramMap, paginator);
			// 保存分页对象
			this.savaPaginator(paginator);
			this.addLog(2, "查询商家员工列表", "查询商家员工列表", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return SUCCESS;
	}

	/**
	 * 新增
	 */
	@RequiresPermissions("addUser")
	public String addUser() {
		return SUCCESS;
	}

	/**
	 * 修改保存，调度Jsp
	 */
	@RequiresPermissions("editUser")
	public String editUser() {
		try {
			userVO = userService.getById(userVO.getId().toString());
			userVO.setPassword(IUserService.PASSWORD_STR);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 保存动作
	 */
	@RequiresPermissions("saveUser")
	public String saveUser() {
		try {
			String customerId = request.getParameter("userVO.customerId");
			if(!StringUtils.isBlank(customerId)){
				userVO.setCustomer(new CustomerVO(Integer.valueOf(customerId)));
			}
			userVO = userService.save(userVO);
			String id = userVO.getId() == null ? "" : userVO.getId().toString();
						String log = "".equals(id) ? "添加商家员工" : "更新商家员工";
						int type = "".equals(id) ? 3:4;
						this.addLog(type, log+id, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "userList");
		return SUCCESS;
	}

	/**
	 * 删除
	 */
	@RequiresPermissions("deleteUser")
	public String deleteUser() {
		try {
			String pkId = request.getParameter("ids");
			userService.remove(Arrays.asList(pkId.split(",")));
			String log = "删除商家员工";
			this.addLog(5, log+pkId, log,getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		request.setAttribute("refreshNavTabId", "userList");
		return SUCCESS;
	}
	
	public String changePassword() {
		try {
			String password = request.getParameter("password");
			UserVO user = new UserVO();
			user.setUserToken(null);
			user.setId(this.getSessionUser().getId());
			user.setPassword(new Md5Hash(password).toHex());
			userService.save(user);
			this.addLog(4, "修改密码", "修改密码", this.getSessionUser());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 查看鿴
	 */
	@RequiresPermissions("viewUser")
	public String viewUser() {
		try {
			String pkId = request.getParameter("ids"); 
			userVO = userService.getById(pkId);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return SUCCESS;

	}

	@RequiresPermissions("importUsers")
	public String importUsers() {
		if (importFile == null)
			return ERROR;
		if (this.importFile != null) {
			try {
				FileInputStream fis = new FileInputStream(importFile);
				SimpleWorkbook fileInDisk = SimpleWorkbook.fromStream(fis);
				fis.close();
				List<UserVO> users = fileInDisk.values(new RowMapper<UserVO>() {
					@Override
					public UserVO mapRow(List<String> celValues) {
						UserVO user = new UserVO();
						user.setEmployId(celValues.get(0));
						user.setName(celValues.get(1));
						user.setAccount(celValues.get(0));
						user.setCustomer(userService.getCurrectUser().getCustomer());
						user.setPassword(new Md5Hash("123456").toHex());
						user.setRole(0);
						user.setEmail(celValues.get(2));
						user.setTel(celValues.get(3));
						user.setCreateDate(new Date());
						user.setStatus(1);
						user.setUserToken(new Md5Hash(celValues.get(0)+"123456").toHex());
						return user;
					}
				});
				userService.insertVos(users);
				this.addLog(4, "导入商家员工", "导入商家员工", this.getSessionUser());
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		request.setAttribute("refreshNavTabId", "userList");
		return SUCCESS;
	}

	public UserVO getUserVO() {
		return userVO;
	}

	public void setUserVO(UserVO userVO) {
		this.userVO = userVO;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public List<UserVO> getUserList() {
		return userList;
	}

	public void setUserList(List<UserVO> userList) {
		this.userList = userList;
	}

	public Collection getRoles() {
		if (roles == null) {
			try {
				Map paramMap = new HashMap();
				if(getSessionUser().getCustomer() != null){
					paramMap.put("customerId", getSessionUser().getCustomer().getId());
				}
				String role = NodePermission.R.getName() + PermissionUtil.colon + RoleType.SHOP.getName() + PermissionUtil.colon + getSessionUser().getRole();
				if(SecurityUtils.getSubject().hasRole(role)){
					paramMap.put("roleType", RoleType.SHOP.getName());
				}
				roles = rolesService.getByMap(paramMap);
			} catch (Exception e) {
			}
		}
		return roles;
	}

	public void setRoles(Collection roles) {
		this.roles = roles;
	}

	public IUserService getUserService() {
		return userService;
	}

	public IRolesService getRolesService() {
		return rolesService;
	}

	public void setRolesService(IRolesService rolesService) {
		this.rolesService = rolesService;
	}

	public File getImportFile() {
		return importFile;
	}

	public void setImportFile(File importFile) {
		this.importFile = importFile;
	}

	public String getSearchType() {
		return searchType;
	}

	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}
	

}